const jwt = require('jsonwebtoken');
const User = require('../models/User');

// 验证token
const auth = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({ message: '请先登录' });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const user = await User.findById(decoded.userId);
    
    if (!user) {
      return res.status(401).json({ message: '用户不存在' });
    }

    req.user = { userId: user._id, user };
    next();
  } catch (error) {
    res.status(401).json({ message: '无效的token',code:4001 });
  }
};

// 管理员权限
const admin = (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({ message: '需要管理员权限' });
  }
  next();
};

module.exports = { auth, admin }; 